import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import { removeToken, setToken } from '@/utils/auth'
import { getUserInfo, login, register, getEnumerator } from '@/services'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {
      name: ''
    },
    token: '',
    regions: [],
    genres: [],
  },
  mutations: {
    ['UPDATE_USER'](state, user) {
      state.user = user
    },
    ['UPDATE_REGIONS'](state, regions) {
      state.regions = regions
    },
    ['UPDATE_GENRES'](state, genres) {
      state.genres = genres
    },
    ['UPDATE_TOKEN'](state, token) {
      state.token = token
    }
  },
  actions: {
    logout({ commit }) {
      commit('UPDATE_USER', {})
      removeToken()
      setTimeout(() => {
        router.push("/login").catch(() => {})
      }, 0)
    },
    async login({ commit }, user) {
      try {
        const { token } = await login(user)
        setToken(token)
        commit('UPDATE_TOKEN', token)
      } catch (err) {
        throw err
      }
    },
    async register({ commit }, user) {
      try {
        await register(user)
      } catch (err) {
        throw err
      }
    },
    async getUserInfo({ commit }) {
      try {
        const data = await getUserInfo()
        commit('UPDATE_USER', data)
      } catch (err) {
        throw err
      }
    },
    async getEnumerator({ commit }) {
      try {
        const data = await getEnumerator()
        const { genres, regions } = data
        commit('UPDATE_GENRES', genres)
        commit('UPDATE_REGIONS', regions)
      } catch (err) {
        throw err
      }
    }
  },
})
